#include <myheader.h>
void mode_to_char(mode_t mode, char *str){
    switch(mode &S_IFMT){
    case S_IFBLK:  str[0] = 'b';            break;
    case S_IFCHR:  str[0] = 'c';        break;
    case S_IFDIR:  str[0] = 'd';               break;
    case S_IFIFO:  str[0] = 'p';               break;
    case S_IFLNK:  str[0] = 'l';                break;
    case S_IFREG:  str[0] = '-';            break;
    case S_IFSOCK: str[0] = 's';                  break;
    default:       str[0] = '*';                break;
    };
    //所有者权限
    str[1] = (mode & 0400) ? 'r':'-';
    str[2] = (mode & 0200) ? 'w':'-';
    str[3] = (mode & 0100) ? 'x':'-';
    //组权限
    str[4] = (mode & 0040) ? 'r':'-';
    str[5] = (mode & 0020) ? 'w':'-';
    str[6] = (mode & 0010) ? 'x':'-';
    //其他用户权限
    str[7] = (mode & 0004) ? 'r':'-';
    str[8] = (mode & 0002) ? 'w':'-';
    str[9] = (mode & 0001) ? 'x':'-';

}
/*Usage pathname  */
int main(int argc, char *argv[])
{
    char *path;
    if(argc == 1){
        //说明打印当前目录
        path = ".";
    }else if(argc == 2){
        path = "argv[1]";

    }else{
        fprintf(stderr,"argc num error!\n");
    }


    DIR *dir_p = opendir(path);
    ERROR_CHECK(dir_p,NULL,"OPENDIR");

    struct dirent *dirent_struct;
    struct stat stat_buf;
    //定义数组记录月份
    char month[][10] = {
        "1月","2月","3月","4月","5月","6月",
        "7月","8月","9月","10月","11月","12月",
    };
    while((dirent_struct = readdir(dir_p)) != NULL){
       //获取绝对路径
        char path_absolute[1024] = {0};
        sprintf(path_absolute,"%s%s%s",path,"/",dirent_struct->d_name); 
        //错误处理
        int ret = stat(path_absolute,&stat_buf);
        ERROR_CHECK(ret,-1,"STAT");
        //权限转换
        char permmision_str[100] = {0};
        mode_to_char(stat_buf.st_mode,permmision_str);
        //用户id,组id转换
        struct passwd *uid_struct = getpwuid(stat_buf.st_uid);
        struct group *gid_struct = getgrgid(stat_buf.st_gid);
        //时间戳转换
        struct tm *timestamp = localtime(&stat_buf.st_mtim.tv_sec);
        printf(" %s %lu  %s  %s     %lu  %s %d %d:%d  %s\n",
               permmision_str,
               stat_buf.st_nlink,
               uid_struct->pw_name,
               gid_struct->gr_name,
               stat_buf.st_size,
               month[timestamp->tm_mon],
               timestamp->tm_mday,
               timestamp->tm_hour,
               timestamp->tm_min,
               dirent_struct->d_name
               );
    
    }
    closedir(dir_p);
    return 0;
}

